package com.card.vault.dao;

import java.util.List;
import org.hibernate.Query;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.card.vault.domain.user.User;
 
@Repository
public class UserDAOImpl implements UserDAO {
	
    @Autowired
    private SessionFactory sessionFactory;
    
    public void saveUser(User user) {
        sessionFactory.getCurrentSession().saveOrUpdate(user);
    }
    
    @SuppressWarnings("unchecked")
	public List<User> userList() {
        return sessionFactory.getCurrentSession().getNamedQuery( User.NamedQuery.USER_FIND_ALL ).list();
    }
    
    public void removeUser(int id) {
        User user = (User) sessionFactory.getCurrentSession().load(User.class, id);
        if (null != user) {
            sessionFactory.getCurrentSession().delete(user);
        }
    }
    
    public User retriveUser(int id){
        Query q = sessionFactory.getCurrentSession().getNamedQuery( User.NamedQuery.USER_FIND_BY_ID );
        q.setInteger("id", id);
        return (User) q.uniqueResult();
    }
    
    public User retriveUser(String name){
        Query q = sessionFactory.getCurrentSession().getNamedQuery( User.NamedQuery.USER_FIND_BY_NAME );
        q.setString("name", name);
        return (User) q.uniqueResult();
    }

	public User findUsersByName(String name){
        Query q = sessionFactory.getCurrentSession().getNamedQuery( User.NamedQuery.USER_FIND_BY_NAME );
        q.setString("name", "%" + name + "%");
        return (User) q.list();
    }
}